package gl.android.biyiqing.fragment;

import gl.adapter.JsonArrayAdapter;
import gl.adapter.JsonArrayImageListAdapter;
import gl.adapter.SimpleAdapter.OnItemChildViewClick;
import gl.android.biyiqing.BuildConfig;
import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.R;
import gl.android.biyiqing.competent.OnToGreetItemClickListener;
import gl.android.biyiqing.competent.OnToUserInfoItemClickListener;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.AndroidUtil;
import gl.uitls.Lg;
import gl.uitls.Tip;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

import com.gitonway.lee.niftynotification.lib.NiftyNotificationView;

public class BaseFragment extends Fragment implements
		BGARefreshLayout.BGARefreshLayoutDelegate {
	protected View rootView;
	public final static String KEY_USER_ID = "userid";
	public final static String KEY_TO_USER_ID = "tuserid";
	public final static String KEY_USER_DATA = "data";
	public final static String KEY_JSON_DATA = "jsondata";
	public final static String KEY_SEX = "sex";
	public boolean DEBUG = BuildConfig.DEBUG;
	protected String userID;
	protected String data;
	protected String NOTFOUND = "没有找到数据";
	protected JSONArray dataJSONArray;
	final String UN_VALUE_STRING = "";
	private BGARefreshLayout mRefreshLayout;
	private BGANormalRefreshViewHolder refreshViewHolder;

	private void initRefreshLayout() {
		if (!getRefreAble()) {
			return;
		}
		mRefreshLayout = (BGARefreshLayout) findViewById(R.id.rl_modulename_refresh);
		if (mRefreshLayout != null) {
			// 设置下拉刷新和上拉加载更多的风格 参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
			 refreshViewHolder = new BGANormalRefreshViewHolder(
					getActivity(), getLoadMoreAble());
			// 设置下拉刷新和上拉加载更多的风格
			mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
			// 为BGARefreshLayout设置代理
			mRefreshLayout.setDelegate(this);
//			 mRefreshLayout.setCustomHeaderView(new TextView(getBaseContext()),
//					 false);
			// mRefreshLayout.setCustomHeaderView(new Button(getBaseContext()),
			// false);
		}
	}
	protected boolean getRefreAble() {
		return false;
	}
	protected boolean getLoadMoreAble(){
		return false;
	}
	@Override
	public void onBGARefreshLayoutBeginRefreshing() {
			
	}

	@Override
	public void onBGARefreshLayoutBeginLoadingMore() {
	}

	public static BaseFragment creatBaseFramgent(String userid,
			Class<? extends BaseFragment> clazz) {
		BaseFragment fragment = null;
		try {
			fragment = clazz.newInstance();
			Bundle args = new Bundle();
			args.putString(KEY_USER_ID, userid);
			fragment.setArguments(args);
		} catch (java.lang.InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return fragment;
	}

	public static BaseFragment creatBaseFramgent(String userid, String data,
			Class<? extends BaseFragment> clazz) {
		BaseFragment fragment = null;
		Bundle args;
		try {
			fragment = clazz.newInstance();
			args = new Bundle();
			args.putString(KEY_USER_ID, userid);
			args.putString(KEY_USER_DATA, data);
			fragment.setArguments(args);
		} catch (java.lang.InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return fragment;
	}

	public static Fragment creatBaseFramgent(Bundle extras,
			Class<? extends BaseFragment> clazz) {
		BaseFragment fragment = null;
		try {
			fragment = clazz.newInstance();
			fragment.setArguments(extras);
		} catch (java.lang.InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		userID = getArguments() == null ? UN_VALUE_STRING : getArguments()
				.getString(KEY_USER_ID);
		data = getArguments() == null ? UN_VALUE_STRING : getArguments()
				.getString(KEY_USER_DATA);
	}

	protected boolean isValueFragment() {
		if (getActivity() == null) {
			if (DEBUG)
				Lg.d("getActivity is null");
			return false;
		}
		return true;
	}

	protected View findViewById(int id) {
		if (rootView == null) {
			return null;
		}
		return rootView.findViewById(id);
	}

	protected void loadDataFromCache(String url) {
		AndroidUtil.getValueFromSharePreferences(url,
				UserManger.getInstance().username);
	}

	protected void appendAbsListView(final AbsListView adpateview, String url,
			Object[] pars) {
		BaseControl.get(url, new AjaxCallBackProxy() {

			@Override
			public void onStart() {
				super.onStart();
				handStart();
			}

			@Override
			public void onSuccess(final String t) {
				
				if (!isValueFragment()) {
					return;
				}
				super.onSuccess(t);
				onAppendAbsListViewCommplete();
				handComplete();
				new Handler().postDelayed(new Runnable() {
					
					@Override
					public void run() {
						try {
							String t1= preFormatJsonData(t);
							final JSONArray jsonArray = new JSONObject(t1)
									.getJSONArray("data");
							if (jsonArray != null) {
								for (int i = 0; i < jsonArray.length(); i++) {
									dataJSONArray.put(jsonArray.getJSONObject(i));
								}
							}
							final ListAdapter adapter = adpateview.getAdapter();
							if (adapter instanceof JsonArrayAdapter) {
								((JsonArrayAdapter) adapter).append(jsonArray);
							}
							adpateview
									.setOnItemClickListener((OnItemClickListener) getOnItemListener(
											new String[0], dataJSONArray));
							
						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
						
					}
				}, 1000);
				
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				if (!isValueFragment()) {
					return;
				}
				handErr();
			}
		}, pars);
	}

	protected void onAppendAbsListViewCommplete() {
		if (mRefreshLayout!=null) {
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					mRefreshLayout.endRefreshing();
				}
			}, 1000);
		
		}

	}

	protected void initAbsListView(final AbsListView adpateview, String url,
			Object[] pars, final int itemLayout, final String[] from,
			final int[] to) {
		BaseControl.get(url, new AjaxCallBackProxy() {
			@Override
			public void onStart() {
				super.onStart();
				handStart();
			}

			@Override
			public void onSuccess(String t) {
				if (!isValueFragment()) {
					return;
				}
				super.onSuccess(t);
				try {
					if (new JSONObject(t).getJSONArray("data") == null
							|| new JSONObject(t).getJSONArray("data").length() <= 0) {
						adpateview.setAdapter(null);
					}
					else {
						dataJSONArray = new JSONObject(t).getJSONArray("data");
						bindDataToAbsListView(adpateview, itemLayout, from, to,
								t);
					}
				} catch (Exception e) {
					e.printStackTrace();
					onFailure(e, 0, e.getMessage());
				} finally {
					System.out.println("onSuccess");
					handHeaderComplete();
					handComplete();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				if (!isValueFragment()) {
					return;
				}
				handErr();
			}
		}, pars);
	}

	protected OnItemChildViewClick getOnItemChildViewCilck() {
		return new OnToGreetItemClickListener(getActivity(), dataJSONArray);
	}

	protected void handHeaderComplete() {
		if (mRefreshLayout!=null) {
			mRefreshLayout.endRefreshing();
		}
	}

	protected void bindDataToAbsListView(final AbsListView adpateview,
			final int itemLayout, final String[] from, final int[] to, String t)
			throws JSONException {
		// pre fromat data
		t = preFormatJsonData(t);
		adpateview.setAdapter(new JsonArrayImageListAdapter(getActivity(),
				new JSONObject(t).get("data").toString(), itemLayout, from, to,
				getOnItemChildViewCilck()));
		adpateview
				.setOnItemClickListener((OnItemClickListener) getOnItemListener(
						from, t));
	}

	protected String preFormatJsonData(String t) {
		return t;
	}

	public Object getOnItemListener(final String[] from, String t)
			throws JSONException {
		return new OnToUserInfoItemClickListener(getActivity(), new JSONObject(
				t).get("data").toString(), from);
	}

	public Object getOnItemListener(final String[] from, JSONArray t)
			throws JSONException {
		return new OnToUserInfoItemClickListener(getActivity(), t.toString(),
				from);
	}

	protected String getUserID() {
		return UserManger.getInstance().userid;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (noticView != null) {
			noticView = null;
		}
	}

	public NiftyNotificationView noticView;

	protected void handErr() {
		if (isValueFragment()) {
			Tip.show(NOTFOUND);
			Tip.dismissStickNotif(noticView);
			handHeaderComplete();
		}
	}

	protected void handStart() {
		// Tip.show(NOTFOUND);
		if (isValueFragment()) {
			if (noticView == null) {
				noticView = Tip.genStickyTip(getActivity(), "loading");
			}
			System.out.println("noticView" + noticView);
			Tip.showStickNotif(noticView);
		}

	}

	protected void handComplete() {
		if (isValueFragment()) {
			Tip.dismissStickNotif(noticView);
		}

	}
	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initRefreshLayout();
	}

	public void startFragmentActivity(Bundle bundle,
			final String basefragmentclassname) {
		final Context activity = getActivity();
		Intent intent = new Intent(activity, FragmentContainerActivity.class);
		bundle.putString(basefragmentclassname,
				VipUpdateFragment.class.getName());
		intent.putExtras(bundle);
		activity.startActivity(intent);
	}
	//
	// public void startFragmentContainerActivity(Bundle bundle,
	// final String basefragmentclassname) {
	// Intent intent = new Intent(getActivity(),
	// FragmentContainerActivity.class);
	// Bundle bundle2 = new Bundle(bundle);
	// bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
	// basefragmentclassname);
	// intent.putExtras(bundle2);
	// getActivity().startActivity(intent);
	// }
}
